package com.ec50n9.server.common

import com.ec50n9.server.module.common.BaseCode
import java.security.MessageDigest

class Md5Utils {
    companion object {
        fun md5(content: String): String {
            val md5String = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
            return try {
                val byteInput: ByteArray = content.encodeToByteArray()
                val mdInst: MessageDigest = MessageDigest.getInstance("MD5")
                mdInst.update(byteInput)
                // Perform hash calculation to obtain ciphertext
                val md: ByteArray = mdInst.digest()

                //Convert ciphertext into hexadecimal string form
                val j = md.size
                val str = CharArray(j * 2)
                var k = 0
                for (byte0 in md) {
                    str[k++] = md5String[byte0.toInt() ushr 4 and 0xf]
                    str[k++] = md5String[byte0.toInt() and 0xf]
                }
                String(str)
            } catch (e: Exception) {
                e.printStackTrace()
                throw ApiException(BaseCode.FAILED, "md5转换失败")
            }
        }
    }
}